package com.lyw.GeoLocationClient.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class StringUtils {

    public static final int KEY_MAX_LENGTH = 45;
    private static final int SHIFT_LENGTH = 6;
    public static String generateKey(String input) {
        char[] arr1 = input.toCharArray();
        leftShiftV2(arr1, SHIFT_LENGTH);

        String shiftOut = new String(arr1);
        String key = stringToMD5(shiftOut);
        if (key.length() > KEY_MAX_LENGTH) {
            return key.substring(0, StringUtils.KEY_MAX_LENGTH);
        }
        return key;
    }

    /**
     * 将字符串转成MD5值
     *
     * @param string
     * @return
     */
    public static String stringToMD5(String string) {
        byte[] hash;

        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }

        return hex.toString();
    }

    public static void leftShiftV2(char[] s, int m) {
        int len = s.length;
        m = m % len;
        reverse(s, 0, m - 1);
        reverse(s, m, len - 1);
        reverse(s, 0, len - 1);
    }

    private static void reverse (char[] s, int from, int to) {
        while(from < to) {
            char c = s[from];
            s[from] = s[to];
            s[to] = c;
            from++;
            to--;
        }
    }

    public static boolean isNullOrEmpty(String str) {
        if (str==null) {
            return true;
        }
        return str.trim().equals("");
    }

}
